package com.ruoyi.web.service.insect.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.annotation.DataSource;
import com.ruoyi.common.enums.DataSourceType;
import com.ruoyi.common.utils.CommonUtils;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.web.domain.insect.InsectRecord;
import com.ruoyi.web.mapper.insect.InsectRecordMapper;
import com.ruoyi.web.pojo.request.insect.*;
import com.ruoyi.web.pojo.vo.insect.*;
import com.ruoyi.web.service.insect.InsectRecordService;
import com.ruoyi.web.utils.wuqing.WQRremoteCall;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.groupingBy;

/**
 * 昆虫识别记录表 服务实现类
 * @author fwx
 * @date 2024-01-22 14:20:01
 */
@Service
public class InsectRecordServiceImpl extends ServiceImpl<InsectRecordMapper, InsectRecord> implements InsectRecordService {

    @Autowired
    private InsectRecordMapper insectRecordMapper;

    @Override
    public List<InsectCountDataVO> getInsectCountData(InsectSumDataRequest request){
        List<InsectCountDataVO> vos = insectRecordMapper.insectNumStatistics(request.getDeviceIds(),
                request.getStartTime(), request.getEndTime());
        return vos;
    }


    @Override
    public InsectCountDataVO insectStatistics(InsectSumDataRequest request){
        return WQRremoteCall.insectStatistics(request);
    }

    @Override
    public List<InsectCountDataVO> getSpInsectCountData(InsectSumDataRequest request){
        return WQRremoteCall.getSpInsectCountData(request);
    }

    @Override
    public List<InsectCountDataVO> getUserInsectCountData(InsectCountDataRequest request){
        return WQRremoteCall.getUserInsectCountData(request);
    }

    /**
     * @desc  计算其他类型昆虫的占比
     * @author fwx 2024/4/12 15:50
     * @param count 要统计其他的前n虫类数量
     **/
    public static List<InsectCountDataVO> computeCount(List<InsectCountDataVO> countData , int count){
        try {
            //如果虫种种类大于7, 把多余7的种类算入其他的种类里
            if(countData.size() > count){

                List<InsectCountDataVO> collect = countData.stream().sorted(Comparator.comparing(InsectCountDataVO::getNums).reversed()).limit(count)
                        .collect(Collectors.toList());

                Integer nums = countData.stream().sorted(Comparator.comparing(InsectCountDataVO::getNums).reversed())
                        .skip(count).mapToInt(InsectCountDataVO::getNums).sum();

                //得到类型的虫数量
                InsectCountDataVO recNums = new InsectCountDataVO();
                recNums.setInsectName("其他");
                recNums.setNums(nums);

                collect.add(recNums);
                getListRatio(collect);
                return collect;
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        getListRatio(countData);
        return countData;
    }

    // 得到总共的虫数量, 并计算集合中虫所占的比例
    private static Integer getListRatio( List<InsectCountDataVO> list){
        Integer nums = list.stream().collect(Collectors.summingInt(InsectCountDataVO::getNums));
        for (InsectCountDataVO recNums : list) {
            if(nums.intValue() > 0){
                int val = recNums.getNums().intValue();

                //保留1位小数
                double i = (double) Math.round ((double) val / nums.intValue() * 1000)   / 10;
                recNums.setRatio(i);
            }
        }

        return nums;
    }

    @Override
    public List<InsectRecord> getHistoryData(InsectHistoryDataRequest request){
        return WQRremoteCall.getHistoryData(request);
    }

    @Override
    public List<InsectAnalysisVO> getCountByInsectName(InsectListRequest request){
        return WQRremoteCall.getCountByInsectName(request);
    }

    @Override
    public Set<String> getInsctName(String start,String end,List<String> deviceIds){

        if(deviceIds.isEmpty()){
            return new HashSet<>();
        }

        InsectTopRequest request = new InsectTopRequest();
        request.setDeviceIds(deviceIds);
        request.setStartTime(start);
        request.setEndTime(end);

        return WQRremoteCall.getInsctName(request);
    }

    @Override
    public List<InsectRecord> getOriginHistoryData(InsectTopRequest request){
        return WQRremoteCall.getOriginHistoryData(request);
    }

    @Override
    public List<InsectRecord> getByPhotoIds(List<Long> photoIds){

        if(CollectionUtils.isEmpty(photoIds)){
            return new ArrayList<>();
        }

        QueryWrapper<InsectRecord> query  = new QueryWrapper<>();
        query.lambda().in(InsectRecord::getPhotoId,photoIds);
        return super.list(query);
    }

    @Override
    public InsectHistoryDataVO getHistoryHandlerData(InsectHistoryDataRequest request){
        return WQRremoteCall.getHistoryHandlerData(request);
    }

    /**
     * @desc  得到设备最新的虫情数据时间
     * @author fwx 2024/4/7 9:12
     **/
    public String getInsectEndTime(String deviceId){
        InsectRecord last = this.getLast(deviceId);
        String endTime = Optional.ofNullable(last).map(rec -> DateUtils.formatDate(rec.getPhotoTime()))
                .orElse(DateUtils.getTomorrowStr());
        return endTime;
    }

    @Override
    public InsectRecord getLast(String deviceId){
        QueryWrapper<InsectRecord> query  = new QueryWrapper<>();
        query.lambda().eq(InsectRecord::getDeviceId,deviceId)
                .orderByDesc(InsectRecord::getPhotoTime).last("limit 1");
        InsectRecord one = super.getOne(query);
        return one;
    }

    /**
     * 获取昆虫始见期的时间
     * @author yaojianbo
     * @date 2024-4-19 14:20:01
     */
    @Override
    public List<InsectCountDataVO> getInsectStartTime(List<String> insectList,InsectCountDataRequest request){
        String insects = insectList.stream().collect(Collectors.joining(","));
        return WQRremoteCall.getInsectStartTime(insects,request);
    }

    public static void main(String[] args) {

    }

}
